#include "ThreadPool.h"
#include <iostream>

using std::cout;
using std::endl;

ThreadPool::ThreadPool(size_t threadNum, size_t queSize)
: _threadNum(threadNum)
, _queSize(queSize)
, _taskQue(_queSize)
, _isExit(false)
{

}

ThreadPool::~ThreadPool()
{
}

void ThreadPool::start()
{
    //创建线程
    for(size_t i = 0; i < _threadNum; ++i)
    {
        _threads.push_back(thread(&ThreadPool::doTask, this));
    }
}

void ThreadPool::stop()
{
    //任务队列非空:阻塞主线程
    if(!_taskQue.empty())
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }

    _isExit = true;
    //重新唤醒所有线程：_isExit现在为true，阻塞在doTask的子线程无法继续执行任务
    _taskQue.wakeup();

    //回收线程
    for(auto &th : _threads)
    {
        th.join();
    }
}

void ThreadPool::addTask(Task &&taskcb)
{
    if(taskcb)
    {
        _taskQue.push(std::move(taskcb));
    }
}

Task ThreadPool::getTask()
{
    return _taskQue.pop();
}

void ThreadPool::doTask()
{
    while(!_isExit)
    {
        //获取一个任务
        Task taskcb = getTask();

        //执行任务
        if(taskcb)
        {
            taskcb();
        }
        else
        {
            cout << ">>task is empty. " << endl;
        }
    }
}
